import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit'
import { v4 as uuidv4 } from 'uuid'
import { BASE_API } from '@/utils'

export interface TodoItem {
  id: string
  content: string
  completed: boolean
}

const initialState: TodoItem[] = []

export const fetchTodos = createAsyncThunk(
  'todos/fetchTodos',
  async (_, { rejectWithValue }) => {
    try {
      const response = await fetch(`${BASE_API}/todos`)
      const { data } = await response.json()
      return data
    } catch (error) {
      return rejectWithValue('无法获取任务列表')
    }
  }
)

const todoSlice = createSlice({
  name: 'todos',
  initialState,
  reducers: {
    addTodo: (state, action: PayloadAction<string>) => {
      state.push({
        id: uuidv4(), 
        content: action.payload,
        completed: false
      })
    },
    toggleTodo: (state, action: PayloadAction<string>) => {
      const todo = state.find(todo => todo.id === action.payload)
      if (todo) {
        todo.completed = !todo.completed
      }
    }
  },
  extraReducers: (builder) => {
    builder.addCase(fetchTodos.fulfilled, (_, action) => {
      return action.payload
    })
    builder.addCase(fetchTodos.rejected, (_, action) => {
      console.error('无法获取任务列表:', action.payload)
    })
  }
})

export const { addTodo, toggleTodo } = todoSlice.actions
export default todoSlice.reducer
